<?php
namespace app\store\model;
use app\common\model\Nearby as NearbyModel;

/**
 * 附近小程序模型
 */
class Nearby extends NearbyModel
{
	/**
     * 添加
     */
    public function add($data)
    {
		if (!isset($data['pic_list']) || empty($data['pic_list'])) {
			$this->error = '请上传门头照片';
			return false;
		}
		//上传永久素材并获取访问链接
		$url = upWechatUrl($data['pic_list']);
		if(!$url){
			$this->error = '门头照片上传到微信端错误';
			return false;
		}
		$data['url'] = $url;
		$data['wxapp_id'] = self::$wxapp_id;
		
		$wxapp = Wxapp::detail();
		//提交到微信端
		$access_token = getAccessToken();
		$url = 'https://api.weixin.qq.com/wxa/addnearbypoi?access_token='.$access_token;
		$post = '{"is_comm_nearby":"1","kf_info":"{\"open_kf\":false,\"kf_headimg\":\"\",\"kf_name\":\"\"}","pic_list":"{\"list\":[\"'.$data['url'].'\"]}","service_infos":"{\"service_infos\":[{\"id\":6,\"type\":1,\"name\":\"点餐\",\"appid\":\"'.$wxapp['app_id'].'\",\"path\":\"pages/index/index\"},{\"id\":1,\"type\":1,\"name\":\"外送\",\"appid\":\"'.$wxapp['app_id'].'\",\"path\":\"pages/index/index\"}]}","store_name":"'.$data['store_name'].'","contract_phone":"'.$data['contract_phone'].'","hour":"'.$data['hour'].'","company_name":"'.$data['company_name'].'","credential":"'.$data['credential'].'","address":"'.$data['address'].'","qualification_list":"","poi_id":""}';
		$result = json_decode(http_request($url,$post),true);
		write_log($post,__DIR__);
		write_log($result,__DIR__);
		if($result['errcode']!=0){
			$this->error = '提交到微信端失败,错误代码：'.$result['errcode'].'错误说明：'.$result['errmsg'];
			return false;
		}
		$data['poi_id'] = $result['data']['poi_id'];
		$data['audit_id'] = $result['data']['audit_id'];
        return $this->allowField(true)->save($data);
    }

    /**
     * 删除
     */
    public function remove()
    {
		$access_token = getAccessToken();
		$url = 'https://api.weixin.qq.com/wxa/delnearbypoi?access_token='.$access_token;
		$data = '{"poi_id":'.$this['poi_id'].'}';
		$result = json_decode(http_request($url,$data),true);
		if($result['errcode']!=0){
			$this->error = '微信端删除失败,错误代码：'.$result['errcode'].'错误说明：'.$result['errmsg'];
			return false;
		}
        return $this->delete();
    }
}
